/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import dao.ClienteDAO;
import dao.ConsertoDAO;
import dao.FabricanteDAO;
import dao.PedidoDAO;
import entity.Cliente;
import entity.Conserto;
import entity.Fabricante;
import entity.Pedido;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.text.ParseException;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.mail.EmailException;
import util.Email;

/**
 *
 * @author Tiago
 */
@WebServlet(name = "ControladoraConserto", urlPatterns = {"/ControladoraConserto"})
public class ControladoraConserto extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException, ParseException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ControladoraConserto</title>");
            out.println("</head>");
            out.println("<body>");

            String action = request.getParameter("action");
            out.println("aqui");

            if (action.equals("cadastrar")) {

                int idPedido = Integer.parseInt(request.getParameter("idpedido"));
                String obs = request.getParameter("conserto");

                PedidoDAO pedidoDAO = new PedidoDAO();
                Pedido pedido = new Pedido();

                ClienteDAO clienteDAO = new ClienteDAO();
                Cliente cliente = new Cliente();
                FabricanteDAO fabricanteDAO = new FabricanteDAO();
                Fabricante fabricante = new Fabricante();
                ConsertoDAO consertoDAO = new ConsertoDAO();

                Conserto conserto = new Conserto();

                pedido = pedidoDAO.getPedido(idPedido);
                pedido.setStatus("finalizar");
                pedidoDAO.altera(pedido);

                GregorianCalendar cal = new GregorianCalendar();
                SimpleDateFormat df = new SimpleDateFormat("dd/mm/yyyy");
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                //Date date = new Date();
                Calendar cal2 = Calendar.getInstance();

                //out.println(dateFormat.format(date));
                conserto.setDt_conserto(cal2.getTime());

                request.setAttribute("pedido", pedido);
                request.setAttribute("conserto", conserto);
                request.setAttribute("fabricante", fabricante);
                request.setAttribute("cliente", cliente);

                RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/cadastra_conserto.jsp");
                rd.forward(request, response);

            } else if (action.equals("inserir")) {

                int idPedido = Integer.parseInt(request.getParameter("idPedido"));

                int idCliente = Integer.parseInt(request.getParameter("idCliente"));

//                String data = request.getParameter("dt_conserto");
                SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                Date dt_conserto = new Date(df.parse(request.getParameter("dt_conserto")).getTime());

                ConsertoDAO consertoDAO = new ConsertoDAO();
                Conserto conserto = new Conserto();

                conserto.setIdPedido(idPedido);
                conserto.setObservacao(request.getParameter("conserto"));
                conserto.setDt_conserto(dt_conserto);
                conserto.setStatus("retirar");

                consertoDAO.insere(conserto);

                Cliente cliente = new Cliente();
                ClienteDAO cliDao = new ClienteDAO();
                cliente = cliDao.buscaCli(idCliente);

                try {
                    Email email = new Email();
                    email.sendEmail(cliente);
                } catch (EmailException e) {
                    throw new RuntimeException(e);
                }
                RequestDispatcher rd = getServletContext().getRequestDispatcher("/pedido_aberto.jsp");
                rd.forward(request, response);
            } else if (action.equals("finalizar")) {
                int idConserto = Integer.parseInt(request.getParameter("idconserto"));
                out.println("aqui");
                ConsertoDAO consertoDAO = new ConsertoDAO();
                consertoDAO.finaliza(idConserto);
                RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/pagamentos_confirmar.jsp");
                rd.forward(request, response);
            }
            else if (action.equals("gerentefina")) {
                int idConserto = Integer.parseInt(request.getParameter("idconserto"));
                out.println("aqui");
                ConsertoDAO consertoDAO = new ConsertoDAO();
                consertoDAO.finaliza(idConserto);
                RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/consertos_retirar.jsp");
                rd.forward(request, response);
            }
            

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ControladoraConserto.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(ControladoraConserto.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ControladoraConserto.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(ControladoraConserto.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
